<?php

/**
 * 本类用于在特采申请当中作判断
 * Auther QiuXiangCheng
 * Date 2016/07/22
 */
class Purchase_Model_ProductCheck extends Model_Base {

	/**
	 * 仓库类型：对应数据库
	 * @var Array
	 */
	public static $stocking_type = [
		1 => '正常备货',
		2 => '活动备货（第三方平台）',
		3 => '活动备货（自营平台）',
		4 => '活动备货（其他）',
	];

	/**
	 * 审核状态：对应数据库
	 * @var Array
	 */
	public static $examine_status = [
		1 => '待一级审核',
		2 => '待二级审核',
		3 => '待三级审核',
		4 => '一级驳回',
		5 => '二级驳回',
		6 => '三级驳回',
		7 => '已通过',
		8 => '已作废',
		9 => '次日作废',
	];

	/**
	 * 特采管理列表显示
	 * @var string
	 */
	public static $examine_status_for_list = [
		2 => '一级审核',
		3 => '二级审核',
		4 => '一级驳回',
		5 => '二级驳回',
		6 => '三级驳回',
		7 => '通过',
		8 => '作废',
		9 => '操作次日作废',
	];

	public static $_examine_type = [
		2 => '审核',
		3 => '审核',
		4 => '驳回',
		5 => '驳回',
		6 => '驳回',
		7 => '通过',
		8 => '作废',
	];

	/**
	 * 采购状态
	 * @var Array
	 */
	public static $purchase_status = [
		1 => '已采购',
		2 => '待采购',
		3 => '部分采购',
		4 => '已失效',
	];

	public static $purchase_examine_level = [
		'wait_for_first_level' => 1,
		'wait_for_second_level' => 2,
		'wait_for_third_level' => 3,
		'reject_once' => 4,
		'reject_twice' => 5,
		'reject_three_times' => 6,
		'examine_success' => 7,
		'examine_in_cancel' => 8,
	];

	private static $purchase_status_by_examine_status = [
		1 => 0,
		2 => 0,
		3 => 0,
		4 => 0,
		5 => 0,
		6 => 0,
		7 => 2,
		8 => 4,
	];

	/**
	 * 将特采的数据审核成功之后取这些字段出来并放入特采需求当中
	 * @var array();
	 */
	private $fieldExamine = [
		'product_name',
		'purchase_num',
		'goods_sn',
		'warehouse_id',
		'warehouse_code',
		'platform_code',
		'apply_num',
		'return_num',
		'stocking_type',
		'apply_user',
		'sale_user',
		'purchase_status',
		'stocking_type_char',
		'expect_from',
		'expect_to',
		'expect_sale_num',
		'remark',
		'latest_time',
		'create_time',
		'update_time',
	];

	const ROLES_FOR_EXAMINE = [4, 8];

	/**
	 * 增加特采申请
	 * @param interval
	 */
	public function Add($data) {

		return $this->db()->insert('p_special_purchase', $data);
	}

	/**
	 * 判断当前SKU的上架时间是否在一个自然月之内
	 * @param $sku
	 * @return Intval
	 */
	public function CheckShelfTime($sku) {

		return $this->db()->fetchOne("CALL GETTHESHELFTIMEOFPRODUCT('{$sku}')");
	}

	/**
	 * 检查产品的销量
	 * return @this
	 */
	public function CheckPropertion($data) {

		return $this->db()->fetchOne('CALL CHECKPROPERTION("' . $data['goods_sn'] . '", "' . $data['warehouse_code'] . '")');
	}

	/**
	 * 取得特采申请列表
	 * @param 要取的字段
	 * @param WHERE/ORDER/LIMIT等条件关键字
	 * @return Array();
	 */
	public function getSpecialApplyList($fields = '*', $get = '', $limit = 15) {

		$where = self::filterSpecialWhere($get);
		// 取特采申请表
		$specialDataList = $this->getSpecialApplyListByID(0, $where, ' ORDER BY psd.create_time DESC ', $limit);

		$ids = array();
		$ware_model = new Application_Model_Warehouse();
		foreach ($specialDataList as $key => $values) {
			if ($platform_code = $values['platform_code']) {
				$warehouse = $ware_model->getWareHouseStock($platform_code, $values['goods_sn']);
				$specialDataList[$key]['base_stock'] = $warehouse['base_stock'];
				$specialDataList[$key]['stock_on_way'] = $warehouse['stock_on_way'];
			}
			// 如果回货数量大于0
			if ($values['return_num'] > 0) {
				$results = Purchase_Model_SpecialDemand::fetchReturnAmount($values['id']);
				if ($results) {
					$specialDataList[$key]['return_log'] = $results;
				}
			}
			$ids[] = $values['id'];
		}
		return ['list' => $specialDataList, 'examine_list' => self::fetchExamineList($ids)];
	}

	/**
	 * 检查存销比
	 * @return float
	 */
	public static function getPropertionForSaving($goods_sn, $warehouse_code) {

		return self::mysql()->fetchOne('CALL CHECKPROPERTION("' . $goods_sn . '", "' . $warehouse_code . '")');
	}

	/**
	 * 将传输过来的GET信息生成where
	 * @param $get参数
	 * @return $where
	 */
	public static function filterSpecialWhere($get) {
		$where = ' WHERE ';
		$where .= self::mysql()->quoteInto(' p.catalog_id in (?) AND ', Application_Model_User::getCategory());
		Helper_Array::filterModels($get);
		if (isset($get['create_time'][0]) && !empty($get['create_time'][0])) {
			if (!empty($get['create_time'][1])) {
				$where .= 'psd.create_time BETWEEN "' . $get['create_time'][0] . '" AND "' . $get['create_time'][1] . '" AND ';
			} else {
				$where .= 'psd.create_time >= "' . $get['create_time'][0] . '" AND ';
			}
		} else if (isset($get['create_time'][1]) && !empty($get['create_time'][1])) {
			$where .= 'psd.create_time <= "' . $get['create_time'][1] . '" AND ';
		} else {
			$where .= 'psd.create_time BETWEEN "' . date("Y-m-d 00:00:00", strtotime('-2 month')) . '" AND "' . date("Y-m-d 23:59:59") . '" AND ';
		}

		if (isset($get['latest_time'][0]) && !empty($get['latest_time'][0])) {
			if (!empty($get['latest_time'][1])) {
				$where .= 'psd.latest_time BETWEEN "' . $get['latest_time'][0] . '" AND "' . $get['latest_time'][1] . '" AND ';
			} else {
				$where .= 'psd.latest_time >= "' . $get['latest_time'][0] . '" AND ';
			}
		} else if (isset($get['latest_time'][1]) && !empty($get['latest_time'][1])) {
			$where .= 'psd.latest_time <= "' . $get['latest_time'][1] . '" AND ';
		}
		if (isset($get['stocking_type']) && $get['stocking_type'] != '-') {
			$where .= 'psd.stocking_type = ' . $get['stocking_type'] . ' AND ';
		}
		if (isset($get['examine_status']) && $get['examine_status'] != '-') {
			$where .= 'psd.examine_status = ' . $get['examine_status'] . ' AND ';
		}
		if (isset($get['purchase_status']) && $get['purchase_status'] != '-') {
			$where .= 'psd.purchase_status = ' . $get['purchase_status'] . ' AND ';
		}
		if (isset($get['billType'])) {
			$where .= 'psd.billType = ' . $get['billType'] . ' AND ';
		}
		if (isset($get['search']) && !empty($get['search']) && $get['search_type'] != '-') {
			switch ($get['search_type']) {
			case 1:
				// $where .= 'psd.goods_sn = "';
				break;
			case 2:
				$where .= 'psd.product_name like "%';
				break;
			case 3:
				$where .= 'psd.apply_user = "';
				break;
			case 4:
				$where .= 'psd.remark = "';
				break;
			}
			if ($get['search_type'] == 1) {
				$goods_sn_arr = explode(',', $get['search']);
				$where .= self::mysql()->quoteInto('psd.goods_sn in (?) AND ', $goods_sn_arr);
			} else {
				if ($get['search_type'] == 2) {
					$where .= $get['search'] . '%" AND ';
				} else {
					$where .= $get['search'] . '" AND ';
				}
			}
		}
		if (isset($get['warehouse_id']) && $get['warehouse_id'] != '-') {
			$where .= 'psd.warehouse_id = ' . $get['warehouse_id'] . ' AND ';
		}
		// 排除作废的单据
		//$where .= 'psd.examine_status != 8';
		strlen($where) == 7 ? $where = '' : $where = rtrim($where, 'AND ');
		return $where;
	}

	/**
	 * 根据SKU取其库存
	 * @param SKU
	 * @return Array()
	 */
	public function getStocksByGoods($goods_sn = [], $fields = '*') {

		if (count($goods_sn) > 0) {
			$where = ' WHERE goods_sn IN("' . implode('","', $goods_sn) . '")';
		} else {
			$where = '';
		}
		$sql = 'SELECT ' . $fields . ' FROM p_product_warehouse_stock' . $where . ' GROUP BY goods_sn';
		return $this->db()->fetchAssoc($sql);
	}

	public function getStockForSpecialData($goods_sn = [], $fields = '*') {

		$sql = 'SELECT ' . $fields . ' FROM p_product_warehouse_stock WHERE goods_sn IN("' . implode('","', $goods_sn) . '")';
		return $this->db()->fetchAll($sql);
	}

	/**
	 * 取各个SKU的特采申请当中最近的一条审核记录
	 * @param SKU在特采申请表中的psd_id
	 * @param 字段
	 * @return Array
	 */
	public function getSpecialExamineList($table, $psds = [], $fields = '*') {

		if (empty($psds)) {
			return [];
		}
		$where = ' WHERE psd_id IN(' . implode(',', $psds) . ')';
		$sql = 'SELECT ' . $fields . ' FROM (SELECT psd_id, user_id, examine_username, examine_time, examine_type FROM ' . $table . ' ORDER BY id DESC) psde ' . $where . ' GROUP BY psde.psd_id';
		return $this->db()->fetchAssoc($sql);
	}

	/**
	 * 取得特采申请列表
	 */
	public function getSpecialApplyListByID($id = 0, $where = '', $order = ' ORDER BY psd.create_time DESC', $limit = '0, 15') {

		$sql = 'SELECT psd.*, p.thumb_url, ppp.purchaser, p.goods_name, pws.stock_can_allot, pws.stock_on_way, pws.stock_wait_for_send, pws.rejects_stock, pws.frozen_stock, pws.virtual_stock, pws.base_stock
			FROM p_special_purchase psd LEFT JOIN p_product_warehouse_stock pws
			ON(psd.goods_sn = pws.goods_sn AND psd.warehouse_code = pws.warehouse_code)
			LEFT JOIN p_product_purchase ppp ON psd.goods_sn = ppp.goods_sn
			LEFT JOIN p_product p ON p.goods_sn = psd.goods_sn
			' . $where . $order . $limit;
		return $this->db()->fetchAll($sql);
	}

	/**
	 * 取得审核/驳回/作废等信息列表
	 * @return
	 */
	public static function fetchExamineList($ids = 0) {

		$where = '';
		if ($ids != 0) {
			$where = ' WHERE psd_id IN("' . implode('","', $ids) . '")';
		}
		$result = self::mysql()->fetchAll('SELECT * FROM p_special_purchase_data_exmaine ' . $where . ' ORDER BY id DESC');
		$data = [];
		foreach ($result as $values) {
			$data[$values['psd_id']][] = $values;
		}
		return $data;
	}

	/**
	 * 通过id找到特采数据
	 * @param ID
	 * @return Array
	 */
	public function getDatasByIDs($ids, $fields = '') {

		empty($fields) && $fields = implode(',', $this->fieldExamine);
		$sql = 'SELECT ' . $fields . ' FROM p_special_purchase WHERE id IN(' . implode(',', $ids) . ')';
		return $this->db()->fetchAll($sql);
	}

	/**
	 * 通过SKU+仓库的方式找出特采需求（只限于未审核的正常需求）
	 * @param Array(goods_sn, wcode)
	 * @return Array
	 */
	public function getSpecialDataDemandByGoodsAndWCode($arr, $fields = '*') {

		$andWhere = '';
		foreach ($arr as $values) {
			$whcode[] = $values['warehouse_code'];
			$goods_sn[] = $values['goods_sn'];
		}
		$andWhere .= ' AND warehouse_code IN("' . implode('","', $whcode) . '") AND goods_sn IN("' . implode('","', $goods_sn) . '")';
		$sql = 'SELECT ' . $fields . ' FROM p_special_purchase WHERE examine_status IN(1, 2)' . $andWhere;
		return $this->db()->fetchAssoc($sql);
	}

	public function updateSpecialData($data, $id) {

		return $this->db()->update('p_special_purchase', $data, 'id = ' . $id);
	}

	/**
	 * 增加审核/作废记录
	 * @param 数据 对应special_data_examine表
	 * @return interger
	 */
	public function insertExamineData($data) {

		return $this->db()->insert('p_special_purchase_data_exmaine', $data);
	}

	/**
	 * 找到下一个要审核的条件
	 */
	public static function FetchNextStatus($id) {

		$purchase_info = self::findExamineLevel($id);
		$next_status = [1 => 2, 2 => 3, 3 => 7];
		if (!isset($next_status[$purchase_info['examine_status']])) {
			return false;
		}
		return $next_status[$purchase_info['examine_status']];
	}

	/**
	 * 传输ID取得本单下一步应该对应的审核等级
	 * 如果返回10 表示这是不需求审核的单据
	 * @param 特采ID
	 */
	public static function FetchNextShouldExamineType($id) {
		// 当前特采单的审核状态和审核等级
		$purchase_info = self::findExamineLevel($id);
		$examineThreeTimes = [1 => 2, 2 => 3, 3 => 7];
		$examineTwice = [1 => 2, 2 => 7];
		$examineOnece = [1 => 7];
		// 无需审核的，已作废和已通过的筛掉
		if ($purchase_info['examine_level'] == 1 || in_array($purchase_info['examine_status'], [7, 8])) {
			return 0;
		}
		switch ($purchase_info['examine_level']) {
		case 2:
			if (isset($examineOnece[$purchase_info['examine_status']])) {
				return $examineOnece[$purchase_info['examine_status']];
			}
			break;
		case 3:
			if (isset($examineTwice[$purchase_info['examine_status']])) {
				return $examineTwice[$purchase_info['examine_status']];
			}
			break;
		case 4:
			if (isset($examineThreeTimes[$purchase_info['examine_status']])) {
				return $examineThreeTimes[$purchase_info['examine_status']];
			}
			break;
		default:
			return 0;
		}
	}

	/**
	 * 通过传输特采ID取得它下一步驳回的级别 如果返回0表示无法确定驳回级别
	 * @param 特采ID
	 * @return interger
	 */
	public static function FetchNextShouldRejectType($id) {

		$purchase_info = self::findExamineLevel($id);
		$rejectType = [1 => 4, 2 => 5, 3 => 6];
		if (isset($rejectType[$purchase_info['examine_status']])) {
			return $rejectType[$purchase_info['examine_status']];
		}
		return 0;
	}

	/**
	 * 通过传输特采ID取得特采名称
	 * @param 特采ID
	 * @return string
	 */
	public static function fetchProductById($purchase_id, $fields = '*') {

		return self::mysql()->fetchAll('SELECT ' . $fields . ' FROM p_special_purchase WHERE id = ' . $purchase_id);
	}

	/**
	 * 批量审核特采数据
	 */
	public function ExamineSpecialData($data) {

		$insert = [];
		$result['status'] = 0;
		$time = date('Y-m-d', time());
		foreach ($data['checkitem'] as $k => $values) {
			switch ($data['examine_type']) {
			case 2:
			case 3:
			case 7:
				// 找出每个单子应当审核到第几级才能被审核通过
				$nextLevel = self::FetchNextShouldExamineType($k);
				if (self::FetchNextStatus($k) != $data['examine_type'] && $nextLevel != 10) {
					continue 2;
				} else if ($nextLevel == 10) {
					$nextLevel = 7;
				}
				break;
			case 4:
			case 5:
			case 6:
			case 8:
				$nextLevel = self::FetchNextShouldRejectType($k);
				if ($nextLevel != $data['examine_type'] && $data['examine_type'] != 8) {
					continue 2;
				} else if ($data['examine_type'] == 8) {
					$nextLevel = 8;
				}
				break;
			}
			$examine_type = $nextLevel;
			if ($nextLevel == 7) {
				$story = new Application_Model_Story;
				$results = self::fetchProductById($k, 'goods_sn, warehouse_code, apply_num, platform_code')[0];
				$r = $story->addSpecialStory($results['goods_sn'], $results['warehouse_code'], $results['apply_num'], trim($results['platform_code'], '-'));
				if ($r === false) {
					$result['message'] = $story->getErrorMsg();
					$result['status'] = 1009;
					return $result;
				}
			}
			$insert[$k]['psd_id'] = $k;
			$insert[$k]['user_id'] = $data['user_id'];
			$insert[$k]['examine_type'] = $examine_type; // 审核状态 examine_status
			$insert[$k]['examine_username'] = $data['user_name'];
			$insert[$k]['examine_time'] = $time;
			!empty($data['examine_reason']) && $insert[$k]['examine_reason'] = $data['examine_reason'];
		}
		if (count($insert) == 0) {
			return $result;
		}
// 			Helper_Array::pr($insert);
		/**
		 * 如果当前设置的审核等级小于单据的等级
		 * 即：假设单据已经为待三级审核 那么如果此时将其设为二级审核或一级审核
		 * 则过滤掉该单据 保留待三级审核的状态进行操作
		 */
		// self::filterExamineStatus($data['checkitem'], $data['examine_type']);
		/**
		 * 插入本次审核记录到关系表
		 * 并更新特采申请单当中的冗余字段
		 */
		if ($this->insertBatch($this->db(), 'p_special_purchase_data_exmaine', $insert)) {
			foreach ($insert as $values) {
				$set = [
					'examine_status' => $values['examine_type'],
					'update_time' => date("Y-m-d H:i:s"),
					'purchase_status' => self::$purchase_status_by_examine_status[$values['examine_type']],
					'examine_user' => Model_User::currentLoginUser()->user_name,
				];
				isset($values['examine_reason']) && $set['remark'] = $values['examine_reason'];
				// 如果当前状态等于审核通过
				if ($values['examine_type'] == 7) {
					// 传输特采数据（申请）ID改变它的类型使之成为特采需求
					$set['billType'] = 1;
				}
				$this->db()->update('p_special_purchase', $set, ' id = ' . $values['psd_id']);
			}
			$result['status'] = 1;
			return $result;
		}
		return false;
	}

	/**
	 * 过滤掉不需要的审核数据
	 * @return 引用
	 */
	public static function filterExamineStatus(&$data, $examine_status) {

		$ids = array_keys($data);
		$sql = 'SELECT id, goods_sn, examine_status FROM p_special_purchase WHERE id IN(' . implode(',', $ids) . ')';
		$result = self::mysql()->fetchAll($sql);
		foreach ($result as $item) {
			if ($examine_status <= $item['examine_status']) {
				unset($data[$item['id']]);
			}
		}
	}

	/**
	 * 通过特采ID取得它的需要审核的等级
	 * @return interger
	 */
	public static function findExamineLevel($pid) {

		$result = self::mysql()->fetchAll('SELECT examine_level, examine_status FROM p_special_purchase WHERE id = ' . $pid);
		if (count($result) == 0) {
			return [];
		}
		return $result[0];
	}

	/**
	 * 根据传输的ID改变特采类型 即：将特采（申请）数据变更变特采需求
	 * @param $id数组形式
	 * @return interger
	 */
	public static function purchaseStatusChange($ids) {

		$sql = 'UPDATE p_special_purchase SET billType = 1 WHERE id IN(' . implode(',', $ids) . ')';
		return self::mysql()->query($sql);
	}

	/*public static function filterEaxmineStatusByWarehouseLevel($data){

			$warehouses = 'SELECT warehouse_code, special_data_examine FROM p_warehouse WHERE warehouse_code IN ("' . implode('", "', array_unique($data)) . '")';
			echo $warehouses;
			die;
		}*/

	/**
	 * 去掉组长审核的状态 让主管审核的状态过来
	 */
	private function fileterStatusForLeader($insert) {

		$t = [];
		// 看看有哪个是最终审核完成的
		foreach ($insert as $values) {
			if ($values['examine_type'] == 5) {
				$t[] = $values;
			}
		}
		return $t;
	}

	/**
	 * 取特采申请数量
	 */
	public static function computSpecialDemandPageAmount($get) {

		$where = self::filterSpecialWhere($get);
		return self::mysql()->fetchOne('SELECT COUNT(*) FROM p_special_purchase psd LEFT JOIN p_product_warehouse_stock pws
			ON(psd.goods_sn = pws.goods_sn AND psd.warehouse_code = pws.warehouse_code)
			LEFT JOIN p_product_purchase ppp ON psd.goods_sn = ppp.goods_sn
			LEFT JOIN p_product p ON p.goods_sn = psd.goods_sn' . $where);
	}

	/**
	 * 取特采需求的数量
	 * @return interger
	 */
	public static function countSepcaialPurchase($get) {

		$where = self::filterSpecialWhere($get);
		$where .= ' GROUP BY psd.platform_code,psd.warehouse_code,psd.goods_sn ';
		$sql = 'SELECT COUNT(*) FROM p_special_purchase psd LEFT JOIN p_product p ON p.goods_sn = psd.goods_sn
				LEFT JOIN p_product_purchase ppp ON psd.goods_sn = ppp.goods_sn
				LEFT JOIN p_product_warehouse_stock pws ON psd.goods_sn = pws.goods_sn AND psd.warehouse_code = pws.warehouse_code' . $where;
		$result = self::mysql()->fetchAll($sql);
		return count($result);
	}

	/**
	 * 生成需求
	 * @param 申请表数据
	 * @param 需求表数据
	 */
	private function fetchSpecialDemand($specialData, $specialDemand) {

		$sqlv = '';
		$update = '';
		foreach ($specialData as $values) {
			// 如果在需求表中没有申请表对应的数据 则插入（以SKU+仓库判断是否有对应数据）
			if (!isset($specialDemand[$values['warehouse_code']]) || $specialDemand[$values['warehouse_code']]['goods_sn'] != $values['goods_sn']) {
				$sqlv .= '(';
				foreach ($values as $key => $fieldsValue) {
					if ($key != 'id' && $key != 'examine_status') {
						!is_numeric($fieldsValue) && $fieldsValue = '"' . $fieldsValue . '"';
						$sqlv .= $fieldsValue . ',';
					}
				}
				$sqlv = rtrim($sqlv, ',') . '),';
			} else {
				$up = 'apply_num = apply_num + ' . $values['apply_num'] . ', purchase_num = purchase_num + ' . $values['purchase_num'] . ', return_num = return_num + ' . $values['return_num'] . ', expect_sale_num = expect_sale_num + ' . $values['expect_sale_num'];
				$where = 'goods_sn = "' . $values['goods_sn'] . '" AND (examine_status = 1 OR examine_status = 2) AND warehouse_code = "' . $values['warehouse_code'] . '"';
				$update = 'UPDATE p_special_purchase SET ' . $up . ' WHERE goods_sn = "' . $values['goods_sn'] . '" AND (examine_status = 1 OR examine_status = 2) AND warehouse_code = "' . $values['warehouse_code'] . '"';
				if (!$this->db()->query($update)) {
					return false;
				}
			}
		}
		if (!empty($sqlv)) {
			$sqlv = 'INSERT INTO p_special_purchase(' . implode(',', $this->fieldExamine) . ') VALUES ' . rtrim($sqlv, ',');
			if (!$this->db()->query(rtrim($sqlv, ','))) {
				return false;
			}
		}
		return true;
	}

	/**
	 * 修改特采申请单的状态
	 * @param 单据ID
	 * @param 状态值 1-待组长审核;2-待主管审核;3-组长驳回;4-主管驳回;5-审核通过;6-已作废
	 * @return interger
	 */
	/*public function updateSpecial($id, $examine_status = 6){

			return $this -> db() -> update('p_special_purchase', ['examine_status' => $examine_status], ['id' => $id]);
		}*/
}